﻿CREATE PROCEDURE [dbo].[ShiftOutDocInsert]
(--Расход по внутреннему перемещению
	@Id int output,
	@DocDate smalldatetime,
	@DocNumber varchar(20) output,
	@ShiftDepartmentId int,  --код подразделения, куда перемещяется товар
	@ParentId int,					 --идентификатор исходного документа
	@Note varchar(250),
	@MD datetime output,
	@MW varchar(50)
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intNextId int
DECLARE @DocTypeId int,	@DepartmentUserId int

SET NOCOUNT ON

IF (@ShiftDepartmentId Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, @intErrCode)
	RETURN @intErrCode
END

IF @DocNumber Is Null
BEGIN
	EXEC [dbo].[GetNextDocNumber] 4, @intRet OUT
	SET @DocNumber = cast( @intRet as varchar(20))
END

IF @DocDate Is Null SET @DocDate = dbo.TodayDate() 
ELSE SET @DocDate = dbo.NormalizeDate(@DocDate)

SELECT @DepartmentUserId = Id FROM CD.DepartmentUsers WHERE Login = suser_sname()

EXEC [dbo].[ProcessStatistic] @Note OUTPUT, @MD OUTPUT, @MW OUTPUT
--получение значения идентификатора
EXEC @intRet = dbo.GetNextCounterFor 'Documents', @intNextId OUTPUT
IF @intRet <> 0 RETURN @intRet

	SET NOCOUNT OFF;
INSERT INTO [CA].[Documents] (Id, [DocTypeId], [DocDate], [DocNumber], 
ShiftDepartmentId, DepartmentUserId, ParentId, [Note], [MD], [MW]) 
VALUES (@intNextId, 4, @DocDate, @DocNumber, 
@ShiftDepartmentId, @DepartmentUserId, @ParentId, @Note, @MD, @MW);

SET @Id = @intNextId
--SELECT Id, DepartmentId, DocTypeId, DocDate, DocNumber, 
--ShiftDepartmentId, DepartmentUserId, Note, MD, MW 
--FROM CA.Documents WHERE (Id = @intNextId)

RETURN 0
